package allenja.cp2011.MVC;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.util.List;

public class MessageController implements ActionListener {
	MessageModel model;
	MessageView view;
	DerbyJdbcDAO derbyDAO;

	// ActionListeners
	public void actionPerformed(ActionEvent e) {
		int actionEventId = 99;
		
		// Covert action command to integers
		if(e.getActionCommand() == "Start") {
			actionEventId = 1;
		} else if (e.getActionCommand() == "Stop") {
			actionEventId = 2;
		} else {
			actionEventId = 99;
		}
		
		// Handle the action commands
		switch (actionEventId) {
		case 1: model.start();
			break;
		case 2: model.stop();
			break;
		case 99: System.out.println("Message Controller : Action performed error #99");
		
		default: System.out.println("Controller: " + e.getActionCommand() + " button was clicked with param " + e.paramString());
		}
	}
	
	// Add model to controller
	public void addModel(MessageModel m) {
		this.model = m;
	}
	
	// Add view to controller
	public void addView(MessageView v) {
		this.view = v;
	}
	
	// Add DAO to controller
	public void addDAO(DerbyJdbcDAO db) {
		this.derbyDAO = db;
	}
	
	// Initialise the port number
	public void initMessageModel(int x) {
		model.setPortNumber(x);
	}
	
	// Initialise the DAO
	public void initDerbyDAO() {
		derbyDAO.createChatUsersTable();
		derbyDAO.createForumTable();
		derbyDAO.createForumMessagesTable();
		derbyDAO.createForumTableToForumMessagesTableJoin();
		
		// Create a time stamp (Date/time)
		Timestamp currentDateTime = new Timestamp(System.currentTimeMillis());
		
		// Hard coded forum creation
		ForumBean testForumBean1 = new ForumBean("TEST Forum1 ~ ", "My testing forum", "Jason", derbyDAO.getNextForumID());
		derbyDAO.addForum(testForumBean1);
		
		// Hard coded forum message creation 1
		ForumMessageBean testForumMessage1 = new ForumMessageBean("TEST Forum1 ~ ", "Test message to forum1", "Jason", currentDateTime, derbyDAO.getNextForumMessageID());
		derbyDAO.addForumMessage(testForumMessage1);
		
		// Hard coded forum message creation 2
		ForumMessageBean testForumMessage2 = new ForumMessageBean("TEST Forum1 ~ ", "Another test message to forum1", "Jason", currentDateTime, derbyDAO.getNextForumMessageID());
		derbyDAO.addForumMessage(testForumMessage2);
		
		List<ChatUserBean> users = derbyDAO.findAllChatUsers();
		
		for (ChatUserBean chatUserBean : users) {
			String userName = chatUserBean.getUserName();
			int userID = chatUserBean.getUserID();
			
			System.out.println("User: " + userName + ":" + userID + " has persisted in the database and will be deleted");
			
			derbyDAO.deleteChatUser(userName, userID);
		}
	}
}
